<template>
  <div class="content-wrapper">
    <div class="content-container">
      <el-form label-width="auto" :inline="true" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="司机编号" class="full-width">
              <el-input v-model="filters.driverNo" placeholder="请输入司机编号" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="司机姓名" class="full-width">
              <el-input v-model="filters.driverName" placeholder="请输入司机姓名" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前位置" class="full-width">
              <el-input v-model="filters.driverCity" placeholder="请输入当前位置" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" class="full-width">
              <el-select v-model="filters.driverState" placeholder="请选择状态" class="full-width">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="已分配车辆" :value="'assigned'"></el-option>
                <el-option label="未分配车辆" :value="'unassigned'"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="驾驶车辆" class="full-width">
              <el-input v-model="filters.vehicleNo" placeholder="请输入驾驶车辆" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" class="full-width">
              <el-input v-model="filters.driverPhone" placeholder="请输入联系方式" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入职时间" class="full-width">
              <el-date-picker
                  v-model="filters.hireDate"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="full-width">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="right full-width" label=" ">
              <el-button-group class="full-width">
                <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
                <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="divider"></div>
      <el-row :gutter="20" class="action-buttons">
        <el-col :span="12">
          <el-button type="primary" plain icon="plus" @click="openDialog(null,false)">新建</el-button>
          <el-button type="danger" plain icon="delete" @click="openBatchDeleteDialog">删除</el-button>
        </el-col>
      </el-row>
      <el-table :data="currentTableData"
                style="width: 100%;
              flex: 1"
                :header-cell-style="{
                  backgroundColor: '#f5f7fa',
                  color: '#333',
                  fontWeight: 'bold',
                  textAlign: 'center',
                  padding: '10px 0'
                }"
                :cell-style="{
                  padding: '10px 0'
                }"
                @selection-change="handleSelectionChange"
                :default-sort="{ prop: 'hireDate', order: 'descending' }">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="driverNo" label="司机编号" width="80"></el-table-column>
        <el-table-column prop="driverName" label="司机姓名" width="80"></el-table-column>
        <el-table-column prop="driverState" label="状态" width="140" align="center">
          <template v-slot="scope">
            <el-tag
                :type="scope.row.driverState === '已分配车辆' ? 'success' : 'warning'"
                disable-transitions
            >{{ scope.row.driverState}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="driverCity" label="当前位置" width="150"></el-table-column>
        <el-table-column prop="vehicleNo" label="驾驶车辆" width="160">
          <template v-slot="scope">
            <span>{{ scope.row.vehicleNo === null ? '暂无' : scope.row.vehicleNo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="driverPhone" label="联系方式" width="160">
        </el-table-column>
        <el-table-column prop="hireDate" label="入职时间" sortable width="160">
          <template v-slot="scope">
            <span>{{ formatDate(scope.row.hireDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wechatState" label="注册状态" width="120" align="center">
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template v-slot="scope">
            <el-button @click="openDialog(scope.row,true)" type="text" icon="EditPen" style="font-size: 13px">修改
            </el-button>
            <el-popconfirm
                width="200"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="是否确定删除？"
                @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button type="text" size="small" icon="delete" style="font-size: 13px">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          class="fixed-pagination">
      </el-pagination>

    </div>
  </div>
  <NewDriverDialog
      v-model="dialogVisible"
      @update:visible="dialogVisible = $event"
      :data="selectedDriver"
      :isEdit="isEdit"
      @save="handleSave"
      visible/>

  <!-- 批量删除弹框 -->
  <el-dialog
      title="删除司机"
      align-center
      v-model="batchDeleteVisible"
      width="60%"
      style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"
  >
    <el-table
        :data="selectedDrivers"
        style="width: 100%;
          margin-bottom: 40px;
          margin-top: 20px;"
        stripe
        border
    >
      <el-table-column prop="driverNo" label="司机编号" width="100"></el-table-column>
      <el-table-column prop="driverName" label="司机姓名" width="150"></el-table-column>
      <el-table-column prop="driverState" label="状态" width="140">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.driverState === 'assigned' ? 'success' : 'warning'"
              disable-transitions
          >{{ scope.row.driverState === 'assigned' ? '已分配车辆' : '未分配车辆' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="driverCity" label="当前位置" width="160"></el-table-column>
      <el-table-column prop="vehicleNo" label="驾驶车辆" width="140"></el-table-column>
      <el-table-column prop="driverPhone" label="联系方式" width="160"></el-table-column>
      <el-table-column prop="hireDate" label="入职时间" sortable width="160">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.hireDate) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="batchDeleteVisible = false" type="primary" plain>取消</el-button>
      <el-button type="danger" @click="handleBatchDelete" plain>确定删除</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import {listDriver, addDriver, updateDriver, deleteDriver, deleteDrivers} from '@/api/delivery/driver.js'; // 引入后端接口封装
import NewDriverDialog from "@/views/delivery/driver/NewDriverDialog.vue";
import {deleteVehicles} from "@/api/delivery/car.js"; // 引入新建/编辑对话框组件

export default {
  components: {NewDriverDialog},
  setup() {
    const filters = reactive({
      driverNo: '',
      driverName: '',
      driverCity: '',
      driverState: null,
      vehicleNo: '',
      driverPhone: '',
      hireDate: [],
    });

    const dialogVisible = ref(false);
    const selectedDriver = ref({});
    const isEdit = ref(false);

    const currentTableData = ref([]);
    const total = ref(0);
    const pageSize = ref(8);
    const currentPage = ref(1);

    const openDialog = (driver, edit) => {
      dialogVisible.value = true;
      isEdit.value = edit;
      selectedDriver.value = driver || {};
    };

    const handleSave = async (driverData) => {
      try {
        if (isEdit.value) {
          await updateDriver(driverData);
        } else {
          await addDriver(driverData);
        }

        dialogVisible.value = false;
        search();
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    const handleDelete = async (row) => {
      try {
        await deleteDriver(row.driverNo);
        if (currentTableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value -= 1;
        }
        search();
      } catch (error) {
        console.error('删除失败:', error);
      }
    };

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    const search = async () => {
      const query = {
        driverNo: filters.driverNo,
        driverName: filters.driverName,
        driverCity: filters.driverCity,
        driverState: filters.driverState,
        vehicleNo: filters.vehicleNo,
        driverPhone: filters.driverPhone,
        startDate: filters.hireDate.length ? formatDate(filters.hireDate[0]) : null,
        endDate: filters.hireDate.length ? formatDate(filters.hireDate[1]) : null,
        page: currentPage.value,
        pageSize: pageSize.value,
      };
      try {
        const response = await listDriver(query);
        currentTableData.value = response.data;
        total.value = response.total;
      } catch (error) {
        console.error('获取司机信息失败:', error);
      }
    };

    //批量删除
    const selectedDrivers = ref([]); // 存储选中的司机信息
    const batchDeleteVisible = ref(false); // 控制批量删除弹框显示

    // 打开批量删除弹框
    const openBatchDeleteDialog = () => {
      if (selectedDrivers.value.length === 0) {
        return ElMessage.warning("请选择要删除的司机！");
      }
      console.log("selectedDrivers", selectedDrivers.value);
      batchDeleteVisible.value = true;
      console.log("batchDeleteVisible", batchDeleteVisible.value);
    };

    // 批量删除
    const handleBatchDelete = async () => {
      if (selectedDrivers.value.length === 0) {
        return ElMessage.warning("请选择要删除的车辆！");
      }
      const driverNos = selectedDrivers.value.map((item) => item.driverNo); // 获取选中车辆的车辆编码
      console.log(driverNos);
      try {
        await deleteDrivers(driverNos); // 调用批量删除接口
        ElMessage.success("批量删除成功！");
        batchDeleteVisible.value = false; // 关闭弹框
        search(); // 刷新表格数据
      } catch (error) {
        console.error("批量删除失败：", error);
      }
    };

    // 表格主选择框选中时触发
    const handleSelectionChange = (rows) => {
      selectedDrivers.value = rows;
    };

    const resetFilters = () => {
      filters.driverNo = '';
      filters.driverName = '';
      filters.driverCity = '';
      filters.driverState = null;
      filters.vehicleNo = '';
      filters.driverPhone = '';
      filters.hireDate = [];
      currentPage.value = 1;
      search();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      search();
    };

    onMounted(() => {
      search();
    });

    return {
      filters,
      currentTableData,
      total,
      pageSize,
      currentPage,
      formatDate,
      search,
      resetFilters,
      handleCurrentChange,
      openDialog,
      handleDelete,
      dialogVisible,
      selectedDriver,
      isEdit,
      handleSave,
      handleSelectionChange,
      selectedDrivers,
      openBatchDeleteDialog,
      batchDeleteVisible,
      handleBatchDelete,
    };
  },
};
</script>

<style scoped>
.el-container {
  height: 100%;
  width: 100%;
}

.content-wrapper {
  background-color: #f5f7fa;
  min-height: inherit;
  display: flex;
  height: calc(100vh - 84px);
  width: 100%;
}

.content-container {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: calc(100% - 40px);
  height: calc(100% - 30px);
  box-sizing: border-box;
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-left: 20px;
  margin-top: 15px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  text-align: center;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.fixed-pagination {
  position: relative;
  right: 0;
  align-self: end;
  margin-top: 20px;
}
</style>
